/*
 * Mutex.h
 *
 *  Created on: Nov 23, 2012
 *      Author: dan
 */

#ifndef MUTEX_H_
#define MUTEX_H_

#include "LamportMutex.h"
#include "TRMutex.h"
#include "exception"
typedef LamportMutex Mutex;

class MutexException:public std::exception{
public:
	virtual const char* what() const _GLIBCXX_USE_NOEXCEPT{ return "Can not lock mutex"; }
};
template<typename MUTEX>
class ScopedLock{
	bool success;
	MUTEX& mutex;
public:

	ScopedLock(MUTEX& mutex,bool waitConnection=false):success(false),mutex(mutex){
		mutex.waitConnection();
		success = mutex.lock();
		if(!success) throw MutexException();
	}
	virtual ~ScopedLock(){
		if(success) mutex.unlock();
	}
	void lock(){ if( mutex.lock() ) return; else throw MutexException(); }
	void unlock(){ mutex.unlock(); }
};

#endif /* MUTEX_H_ */
